import { getDefaultFields } from '../utils';

module.exports = app => {
	const DataTypes = app.Sequelize;

	const Model = app.model.define('Goods', {
		id: {
			type: DataTypes.INTEGER(11).UNSIGNED,
			allowNull: false,
			primaryKey: true,
			autoIncrement: true
		},
		category_id: {
			type: DataTypes.INTEGER(11).UNSIGNED,
			allowNull: false,
			defaultValue: '0',
			comment: '商品分类'
		},
		name: {
			type: DataTypes.STRING(120),
			allowNull: false,
			defaultValue: '',
			comment: '商品名称'
		},
		nick: {
			type: DataTypes.STRING(120),
			allowNull: true,
			defaultValue: '',
			comment: '宝贝昵称'
		},
		keywords: {
			type: DataTypes.STRING(255),
			allowNull: false,
			defaultValue: '',
			comment: '关键字'
		},
		brief: {
			type: DataTypes.STRING(500),
			allowNull: false,
			defaultValue: '',
			comment: '简介'
		},
		desc: {
			type: DataTypes.TEXT,
			allowNull: true,
			comment: '描述'
		},
		main_pic: {
			type: DataTypes.STRING(255),
			allowNull: false,
			comment: '主图'
		},
		sales_volume: {
			type: DataTypes.INTEGER(11).UNSIGNED,
			allowNull: true,
			defaultValue: '0',
			comment: '商品总销量'
		},
		online: {
			type: DataTypes.INTEGER(1).UNSIGNED,
			allowNull: false,
			defaultValue: '0',
            comment: '是否上架，0->不上架，1->上架',
		},
		sort: {
			type: DataTypes.INTEGER(4).UNSIGNED,
			allowNull: false,
			defaultValue: '0',
			comment: '排序'
		},
		is_delete: {
			type: DataTypes.INTEGER(1).UNSIGNED,
			allowNull: false,
			defaultValue: '0',
            comment: '是否删除，0->存在，1->删除'
		},
		is_limited: {
			type: DataTypes.INTEGER(1).UNSIGNED,
			allowNull: true,
			defaultValue: '0',
            comment: '是否超过限制，0->没有超过限制，1->超过限制'
		},
		stock: {
			type: DataTypes.INTEGER(11),
			allowNull: true,
			comment: '库存'
		},
		cost_price: {
			type: DataTypes.INTEGER(11),
			allowNull: true,
			comment: '成本价格'
		},
		market_price: {
			type: DataTypes.INTEGER(11),
			allowNull: true,
			comment: '原价（划线价格）'
		},
		price: {
			type: DataTypes.INTEGER(11),
			allowNull: false,
			comment: '销售价格'
		},
        ...getDefaultFields()
	}, {
		tableName: 'goods',
		timestamps: false
	});

	Model.sync({ alter: true });
	Model.associate = function () {
        app.model.Goods.hasOne(app.model.Category, {
            foreignKey: 'id',
            constraints: false,
            sourceKey: 'category_id'
		});
		app.model.Goods.hasMany(app.model.GoodsGallery, {
            foreignKey: 'goods_id',
			constraints: false,
			as: 'banner',
            sourceKey: 'id'
        });
		app.model.Goods.hasMany(app.model.GoodsSku, {
            foreignKey: 'goods_id',
            constraints: false,
            sourceKey: 'id'
        });
		app.model.Goods.hasMany(app.model.GoodsAttr, {
            foreignKey: 'goods_id',
            constraints: false,
            sourceKey: 'id'
		});
		app.model.Goods.belongsToMany(app.model.Market, {
			through: app.model.MarketGoods,
			foreignKey: 'goods_id',
			otherKey: 'market_id'
		});
	}

	return Model;
};
